package com.maker.mcp.client.service.impl;

import com.maker.mcp.client.service.RagService;
import com.maker.mcp.client.utils.CustomTextSplitter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.document.Document;
import org.springframework.ai.embedding.EmbeddingModel;
import org.springframework.ai.reader.TextReader;
import org.springframework.ai.transformer.splitter.TokenTextSplitter;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.ai.vectorstore.redis.RedisVectorStore;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.HexFormat;
import java.util.List;

@Service
@RequiredArgsConstructor
@Slf4j
public class RagServiceImpl implements RagService {

    private final  RedisVectorStore redisVectorStore;

    private final EmbeddingModel embeddingModel;
    @Override
    public List<Document> loadText(Resource resource, String fileName) {
        //加载读取文档
        TextReader textReader = new TextReader(resource);
        //只要代码里  metadata.put("fileName",xxx) ，
        // 就必须在 yml 里列出  metadata-fields: [fileName] ，
        // 否则 Spring-AI 会自动拼过滤条件 → Redis 找不到字段 → 永远 0 条。
        //删索引 → 重启 → 重写数据，即可立即看到命中数从 0 变 ≥3。
        textReader.getCustomMetadata().put("fileName", fileName);

        List<Document> documentList = textReader.get();
        //默认的文本切割器
        TokenTextSplitter tokenTextSplitter = new TokenTextSplitter();
        List<Document> splitDocuments = tokenTextSplitter.apply(documentList);
//        //按“空白行”切分文本段落的简洁写法，等价于“段落分割器”
//        CustomTextSplitter tokenTextSplitter = new CustomTextSplitter();
//        List<Document> splitDocuments = tokenTextSplitter.apply(documentList);
        System.out.println("splitDocuments:"+splitDocuments);

        //向量存储
        redisVectorStore.add(splitDocuments);

        return splitDocuments;
    }

    @Override
    public List<Document> doSearch(String question) {
        List<Document> documents = redisVectorStore.similaritySearch(question);
//
//
//        List<Document> documents = redisVectorStore.similaritySearch(new SearchRequest.Builder()
//                .query(question)
//                .topK(5)
//                .similarityThreshold(0.0f)
//                .build());
        return documents;
    }
}
